package com.jyniubi.gmall.payment.interceptor;

import com.jyniubi.gmall.payment.pojo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userIdStr = request.getHeader("userId");
        String username = request.getHeader("username");

        log.info("Received request with userId: {}, username: {}", userIdStr, username);
        if (userIdStr == null || userIdStr.isEmpty()) {
            log.error("userId is missing or empty");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.getWriter().write("userId is required");
            return false;
        }
        try {
            Long userId = Long.valueOf(userIdStr);
            THREAD_LOCAL.set(new UserInfo(userId, null, username));
        } catch (NumberFormatException e) {
            log.error("Invalid userId format: {}", userIdStr, e);
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.getWriter().write("Invalid userId format");
            return false;
        }
        return true;
    }
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 调用删除方法，是必须选项。因为使用的是tomcat线程池，请求结束后，线程不会结束。
        // 如果不手动删除线程变量，可能会导致内存泄漏
        THREAD_LOCAL.remove();
    }
}
